package com.yita.fruit.servlets;

import com.sun.xml.internal.ws.api.ha.StickyFeature;
import com.yita.fruit.dao.FruitDAO;
import com.yita.fruit.dao.Impl.FruitDaoImpl;
import com.yita.fruit.pojo.Fruit;
import com.yita.myssm.myspringmvc.ViewBaseServlet;
import sun.plugin2.ipc.InProcEvent;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/index")
public class IndexServlet extends ViewBaseServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String oper = req.getParameter("oper");
        String keyword = "";
        int page = 1;
        HttpSession session = req.getSession();

        if ("search".equals(oper)) {
            keyword = req.getParameter("keyword");
            if (keyword == null) {
                keyword = "";
            }
            session.setAttribute("keyword", keyword);
        } else {
            String pageNoStr = req.getParameter("pageNo");
            if (pageNoStr != null && pageNoStr.length() > 0) {
                page = Integer.parseInt(pageNoStr);
            }
            keyword = (String) session.getAttribute("keyword");
            if (keyword == null) {
                keyword = "";
            }
        }


        FruitDAO fruitDao = new FruitDaoImpl();
        int row = 5;
        List<Fruit> fruitList = fruitDao.getFruitList(page, row, keyword);


        int fruitCount = fruitDao.getFruitCount(keyword);
        int pageCount = fruitCount / row + (fruitCount%row!=0?1:0);
        session.setAttribute("pageCount", pageCount);


        session.setAttribute("fruitList", fruitList);
        session.setAttribute("pageNo", page);
        //逻辑视图名称:index
        //物理视图名称: view-prefix +逻辑视图名称 + view-suffix
        //所以index的物理试题名称是:/ index .html

        processTemplate("index", req, resp);

    }
}
